<template>
  <div class="p-2">
    <div class="viewBox">
      <div class="title-item">
        <span class="line-box"></span><span>{{ title }}</span>
      </div>
      <el-form ref="testTimeTableFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="课程" prop="courseId">
          <!-- <el-input v-model="form.courseId" placeholder="请输入课程" v-if="type != 2" />
          <div v-else>{{ form.courseId }}</div> -->

          <el-select v-model="form.courseId" placeholder="请选择课程" v-if="type != 2">
            <el-option v-for="dict in testList" :key="dict.id" :label="dict.testName" :value="dict.id"></el-option>
          </el-select>
          <div v-else>{{ testName }}</div>
        </el-form-item>
        <!-- <el-form-item label="学年" prop="courseYear">
          <el-select v-model="form.courseYear" placeholder="请选择学年" clearable v-if="type != 2">
            <el-option v-for="dict in sys_stu_year" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
          <div v-else><dict-tag :options="sys_grade" :value="form.courseGrade" /></div>
        </el-form-item> -->
        <el-form-item label="学段" prop="coursePeriod">
          <!-- <el-input v-model="form.coursePeriod" placeholder="请输入学段" /> -->
          <el-select v-model="form.coursePeriod" placeholder="请输入学段" clearable v-if="type != 2">
            <el-option v-for="dict in sys_period" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
          <div v-else><dict-tag :options="sys_period" :value="form.coursePeriod" /></div>
        </el-form-item>
        <el-form-item label="年级" prop="courseGrade">
          <el-select v-model="form.courseGrade" placeholder="请选择年级" clearable v-if="type != 2">
            <el-option v-for="dict in sys_grade" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
          <div v-else><dict-tag :options="sys_grade" :value="form.courseGrade" /></div>
        </el-form-item>
        <el-form-item label="学科" prop="courseSubject">
          <el-select v-model="form.courseSubject" clearable placeholder="请选择学科" v-if="type != 2">
            <el-option v-for="dict in subjectOptions" :key="dict.id" :label="dict.subjectName" :value="dict.id"></el-option>
          </el-select>
          <div v-else>{{ getSubjectNameById(subjectOptions, form.courseSubject) }}</div>
        </el-form-item>
        <el-form-item label="授课地区" prop="courseArea">
          <!-- <el-input v-model="form.courseArea" placeholder="请输入授课地区" v-if="type != 2" /> -->
          <el-cascader
            v-if="type != 2"
            clearable
            filterable
            placeholder="省/市/区"
            :options="addRessList"
            :props="cityProps"
            v-model="form.courseAreaList"
            popper-class="pc-sel-area-cascader"
            @change="courseAreaChange"
          />
          <div v-else>{{ getFullAddress(form.courseArea) }}</div>
        </el-form-item>
        <el-form-item label="授课学校" prop="courseDept" v-if="userId === 1 && tenantDisabled">
          <!-- <el-tree-select
            v-if="type != 2"
            clearable
            filterable
            v-model="form.courseDept"
            :data="deptOptions"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
            value-key="deptId"
            placeholder="请选择学校"
            :render-after-expand="false"
          /> -->
          <el-select v-if="type != 2 " v-model="form.courseDeptList" placeholder="请选择学校" multiple >
            <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
          </el-select>
          <div v-else> 
            {{getTenantById(tenantOptions,form.courseDept)}}
          </div>
        </el-form-item>
        <el-form-item label="授课时间" prop="courseDate">
          <el-date-picker
            v-if="type != 2"
            clearable
            v-model="form.courseDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="年/月/日"
            :disabledDate = "disabledTestDateFun"
          >
          </el-date-picker>
          <div v-if="type != 2" style="margin: 0 5px">-</div>
          <el-date-picker
            v-if="type != 2"
            clearable
            v-model="form.courseDateEnd"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="年/月/日"
            :disabledDate = "disabledEndDateFun"
          >
          </el-date-picker>

          <div v-else>{{ form.courseDate }} - {{ form.courseDateEnd }}</div>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="type != 2">确 定</el-button>
        <el-button @click="edit" v-if="type != 0 && type != 1">编辑</el-button>

        <el-button @click="cancel">取 消</el-button>
        <el-button @click="handleDelete" v-if="type != 0 && type != 1">删除</el-button>
      </div>
    </div>
  </div>
</template>

<script setup name="TestTimeTable" lang="ts">
import { listTestTimeTable, getTestTimeTable, delTestTimeTable, addTestTimeTable, updateTestTimeTable } from '@/api/core/testTimeTable';
import { TestTimeTableVO, TestTimeTableQuery, TestTimeTableForm } from '@/api/core/testTimeTable/types';
import { listDept } from '@/api/system/dept'; //学校
import { DeptVO } from '@/api/system/dept/types'; //学校
const route = useRoute();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no, sys_period, sys_grade,sys_stu_year } = toRefs<any>(proxy?.useDict('sys_yes_no', 'sys_period', 'sys_grade','sys_stu_year'));

const buttonLoading = ref(false);

const testTimeTableFormRef = ref<ElFormInstance>();

// 共有数据方法
import { getSubjectNameById,getTenantById } from '@/utils/index';
import { useSubjectList } from '@/composables/useSubjectList';
const { subjectOptions, fetchSubjectList } = useSubjectList();
//学校改租户数据
import { useTenantlList } from '@/composables/useSchoolList';
const { tenantOptions, fetchTenantlList,tenantDisabled} = useTenantlList()
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantId = ref(userStore.tenantId)

import cityData from '@/assets/json/pca-code.json';
const addRessList = ref(cityData);
const cityProps = reactive({
  emitPath: false,
  value: 'code', //指定选项的值为addresslist对象的code属性
  label: 'name', //指定选项标签为addresslist对象的name属性
  children: 'children', //指定选项的子选项为addresslist对象的children属性
  multiple: true,//是否可多选
});
const disabledTestDateFun = time =>{
  if(form.value.courseDateEnd){
    const startTime = form.value.courseDateEnd.substr(0,10) + ' 00:00:00';
    const endTime = form.value.courseDateEnd.substr(0,10) +  ' 23:59:59';
    return time.getTime() < new Date(startTime).getTime() || time.getTime() > new Date(endTime).getTime()
  }
}
const disabledEndDateFun = time =>{
  if(form.value.courseDate){
    const startTime = form.value.courseDate.substr(0,10) + ' 00:00:00';
    const endTime = form.value.courseDate.substr(0,10) +  ' 23:59:59';
    return time.getTime() < new Date(startTime).getTime() || time.getTime() > new Date(endTime).getTime()
  }
}
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const loading = ref(true);
//
const title = ref('');
const formId = ref('');
const type = ref<string | number>();
// 学校
interface DeptOptionsType {
  deptId: number | string;
  deptName: string;
  children: DeptOptionsType[];
}
const deptOptions = ref<DeptOptionsType[]>([]); //学校
//
// 实验目录
import { listTest } from '@/api/core/test';
const testList = ref([]);
const testName = ref('');

const dialogVisible = ref(false);
const initFormData: TestTimeTableForm = {
  courseId: undefined,
  // courseYear:undefined,//学年
  coursePeriod: undefined,
  courseGrade: undefined,
  courseSubject: undefined,
  // courseArea: undefined,
  courseAreaList:[],
  // courseDept: undefined,
  courseDeptList: [],
  courseDate: undefined,
  courseDateEnd: undefined
};
const data = reactive<PageData<TestTimeTableForm, TestTimeTableQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    courseId: undefined,
    coursePeriod: undefined,
    courseGrade: undefined,
    courseSubject: undefined,
    courseArea: undefined,
    courseDept: undefined,
    courseDate: undefined,
    courseDateEnd: undefined,
    params: {}
  },
  rules: {
    courseId: [{ required: true, message: '课程不能为空', trigger: 'blur' }],
    coursePeriod: [{ required: true, message: '学段不能为空', trigger: 'change' }],
    courseGrade: [{ required: true, message: '年级(班级)不能为空', trigger: 'blur' }],
    courseSubject: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
    courseAreaList: [{ required: true, message: '授课地区不能为空', trigger: 'blur' }],
    // courseDeptList: [{ required: true, message: '授课学校不能为空', trigger: 'blur' }],
    courseDate: [{ required: true, message: '授课开始时间不能为空', trigger: 'blur' }],
    courseDateEnd: [{ required: true, message: '授课结束时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getFullAddress = (districtId) => {
  const findDistrict = (list, id, path = []) => {
    for (let item of list) {
      if (item.code === id) {
        path.push(item.name);
        return path.join('/');
      }
      if (item.children && item.children.length > 0) {
        if (item.name !== '市辖区') {
          path.push(item.name);
        }
        const result = findDistrict(item.children, id, path);
        if (result) {
          return result;
        }
        if (item.name !== '市辖区') {
          path.pop(); // 回溯
        }
      }
    }
    return null;
  };

  const address = findDistrict(addRessList.value, districtId);
  return address || '未知';
};
const courseAreaChange = (e) =>{
  console.log('地区选择',e)
}
/** 查询学校列表 */
const getSchoolList = async () => {
  const res = await listDept();
  const data = proxy?.handleTree<DeptOptionsType>(res.data, 'deptId');
  if (data) {
    deptOptions.value = data;
  }
};
const edit = () => {
  type.value = '1';
  title.value = '编辑';
};

/** 取消按钮 */

const cancel = () => {
  reset();
  proxy?.$router.go(-1);
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  testTimeTableFormRef.value?.resetFields();
};

const submitForm = () => {
  testTimeTableFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      //如果当前登录用户是管理员，学校用选择字段；
      if(userId.value === 1 && tenantDisabled.value){

      }else{ 
        //是租户，学校默认传当前用户tenantId
        form.value.courseDept = tenantId;
      }
      try {
        if (form.value.id) {
          await updateTestTimeTable(form.value);
          proxy?.$modal.msgSuccess('编辑成功');
        } else {
          await addTestTimeTable(form.value);
          proxy?.$modal.msgSuccess('新增成功');
        }
        proxy?.$router.go(-1);
      } catch (error) {
        console.error('Submit failed:', error);
        proxy?.$modal.msgError('操作失败，请稍后再试');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async () => {
  await proxy?.$modal.confirm('是否确认删除教学实验排课编号为"' + form.value.id + '"的数据项？').finally(() => (loading.value = false));
  await delTestTimeTable(form.value.id);
  proxy?.$modal.msgSuccess('删除成功');
  proxy?.$router.go(-1);
};

/** 获取数据 */
(async () => {
  formId.value = route.query && (route.query.id as string);
  type.value = route.query && (route.query.type as string);
  if (type.value == '0') {
    title.value = '新增';
  } else if (type.value == '1') {
    title.value = '编辑';
  } else {
    title.value = '查看';
  }
  if (formId.value) {
    const res = await getTestTimeTable(formId.value);
    res.data.courseArea = res.data?res.data.courseArea?res.data.courseArea+'':'':'';
    console.log('===区域回显',res.data.courseArea);
    Object.assign(form.value, res.data);
  }
  try {
    const response = await listTest();
    if (response && response.rows) {
      testList.value = response.rows.map((item) => ({ id: item.id, testName: item.testName }));
      // 查找 form.courseId 对应的 testName
      if (form.value.courseId) {
        const selectedTest = testList.value.find((test) => test.id === form.value.courseId);
        if (selectedTest) {
          testName.value = selectedTest.testName;
        }
      }
    }
  } catch (error) {
    console.error('Error fetching test list:', error);
  }
  fetchSubjectList();
  getSchoolList();
})();
</script>
<style lang="scss" scoped>
.viewBox {
  margin: 15px 15px 80px 15px;
  .title-item {
    display: flex;
    align-items: center;
    height: 24px;
    line-height: 24px;
    font-size: 20px;
    margin: 30px 0 20px;
    span {
      display: inline-block;
      margin: 0 5px;
    }
    .line-box {
      width: 4px;
      height: 24px;
      background: #05afea;
    }
  }
  .topTit {
    margin-top: 10px;
  }
  .el-form-item--default {
    margin: 15px 30px;
  }
  :deep(.el-textarea__inner) {
    width: 300px !important;
  }
  .el-input {
    width: 300px;
  }
  .el-select {
    width: 300px;
  }
  .dialog-footer {
    margin-top: 100px;
    text-align: center;
  }
}

.imgView-box {
  :deep(.el-upload-list--picture-card .el-upload-list__item-actions .el-upload-list__item-delete) {
    display: none !important;
  }
  :deep(.el-upload--picture-card) {
    display: none !important;
  }

  :deep(.el-upload-list__item.is-success .el-upload-list__item-status-label),
  :deep(.el-icon--close-tip),
  :deep(.el-icon--close) {
    display: none !important;
  }
}
</style>
